package com.diyphonegadgets.videoreceiver;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.util.*;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;

public class VideoStreamReceiverActivity extends Activity
{
	ImageView iv;
	Bitmap bmp;
	int port =8123;
	ServerSocket serverSocket;
	Socket client;
	InputStream inputStream;
	final String TAG = "downStream [DownStream]";
	boolean exception=false;
	DownStreamer ds;
	Thread streamerThread;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		
		iv=(ImageView)findViewById(R.id.lpimg);
		
		
		ds=new DownStreamer(port);
		streamerThread=new Thread(ds);
		streamerThread.start();
	}
    
    
	final Handler messageHandler = new Handler() 
	{

		@Override
		public void handleMessage(Message msg) 
		{  
			iv.setImageBitmap(bmp);
        }
	};
    
 public void resetConnection(){
	 
		try
		{
			serverSocket.close();
			client.close();
			inputStream.close();
			
			serverSocket=null;
			client=null;
			
			ds=null;
			streamerThread=null;
			
			Thread.sleep(500);

		}
		catch(Exception ex)
		{
		}
	 
		
		
		ds=new DownStreamer(port);
		streamerThread=new Thread(ds);
		streamerThread.start();
	 
 }

  
    public static byte[] readBytes(Socket socket, int aMaxBytes) throws IOException {
   
		Log.i("","1111");

		
		InputStream in=new FlushedInputStream (socket.getInputStream());
    	
		  byte[] input = new byte[aMaxBytes];
		    for (int i = 0; i < input.length; i++) {
		      int b = in.read( );

		      if (b  == -1) 
		       break;
		      input[i] = (byte) b;
		    }
			return input;
    	}
    
    
    
    
  
    
    class DownStreamer implements Runnable
	{
	
		
		public DownStreamer(int p)
		{
			p=port;
		}
		
		@Override
		public void run()
		{
			
				try
				{
					exception=false;

					Log.i(TAG,"Creating down stream server...");
					serverSocket=new ServerSocket(8123);
					Log.i(TAG,"Down stream server created.");
				}
				catch(Exception ex)
				{
					Log.e(TAG,"Exception in creating down stream server...\n" + ex.toString());
					exception=true;
					resetConnection();

				}
				
			
				try
				{
					Log.i(TAG,"Waiting for connection...");
					client=serverSocket.accept();
		
					Log.i(TAG,"Done.");
				}
				catch(Exception ex)
				{
					Log.e(TAG,"Exception in creating connection...\n" + ex.toString());
					exception=true;
					resetConnection();

				}
				
			

				
			
				while(true && !exception)
				{
					
					
				try
				{   
					
					
					
					Log.i(TAG,"Connected.\nObtaining input stream...");
					
					
					try {
						inputStream=client.getInputStream();
					} catch (IOException e) {
						exception=true;
						e.printStackTrace();
						resetConnection();

					}


				
                    if(inputStream!=null)
                    	
                    	try{
					bmp = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                    	}
                    
                    catch (Exception e) {
						exception=true;
						e.printStackTrace();
						resetConnection();

					}



					
					if(bmp != null)
					{
						
						messageHandler.sendEmptyMessage(0);
						Log.i(TAG,"Done.");

					}

				
					
				}
				catch(Exception ex)
				{
					Log.e(TAG,"Exception in reading...\n" + ex.toString()); 
					exception=true;
					resetConnection();

				}
			
			}
			
				resetConnection();
		}
	}	
    
    
    
    static class FlushedInputStream extends FilterInputStream {
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break;  // we reached EOF
                    } else {
                        bytesSkipped = 1; // we read one byte
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }
}	